package com.cardvalue.sys.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.cardvalue.sys.R;
import com.cardvalue.sys.adapter.MyFragmentPageAdapter;
import com.cardvalue.sys.adapter.ScreenAdapter;
import com.cardvalue.sys.base.BaseFragment;
import com.cardvalue.sys.tool.MViewPager;
import com.cardvalue.sys.tool.SyncHorizontalScrollView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

public class HomePageFragment extends BaseFragment {
    public static final String ARGUMENTS_NAME = "arg";
    @Bind(R.id.rl_nav)  RelativeLayout mRlnavView;//ScrollView里面的相对布局
    @Bind(R.id.mHsv)   SyncHorizontalScrollView mHsv;//滑动的ScrollView
    @Bind(R.id.rg_nav_content) RadioGroup mRgnavView;//RadioGroup的id
    @Bind(R.id.iv_nav_indicator)  ImageView mImgNavIndicatorView;//文字外面的边框
    @Bind(R.id.iv_nav_left)  ImageView iv_nav_left;//左边的图片
    @Bind(R.id.iv_nav_right)  ImageView iv_nav_right;//右边的图片
    @Bind(R.id.drop_down_layout)  LinearLayout view1;
    @Bind(R.id.mask)  View mask;//阴影层
    @Bind(R.id.tv_step) TextView tv_step;//切换步骤
    @Bind(R.id.screen_grid_view)  GridView gridView;//GridView
    @Bind(R.id.iv_add) ImageView iv_add;//加号


   // private ViewPager mViewPager;
    public static  ViewPager mViewPager;
    private int indicatorWidth;
    public static String[] title = { "基础资料", "上传资料", "处理中"};	//标题
    private LayoutInflater mInflater;
    private MyFragmentPageAdapter mAdapter = null;
    private Animation dropdownIn, dropdownOut, dropdownMaskOut,rotateIn,rotateOut;
    private boolean isOpen = true;
    private List<Map<String, Object>> scrrenList = new ArrayList<Map<String, Object>>();
    private ScreenAdapter screenAdapter;
    private   View  view;
    private   ImageView iv_left;//head 的左边图片   右边的加号
    private int n=3;//就是显示有标题
    private int mScreenWidth = 0;
    private static int columnSelectIndex = 0;  /** 当前选中的栏目*/
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_homepage, container, false);
        ButterKnife.bind(this,view);
        Log.e("BasicFragment", "homepage======");
        initView();
        initNavigationHSV();
        setListener();
        return view;
    }


    private void initView() {
        mViewPager = (ViewPager)view.findViewById(R.id.mViewPager);
        iv_left=(ImageView)view.findViewById(R.id.iv_left);
        mask.setVisibility(View.GONE);
        view1.setVisibility(View.GONE);
        dropdownIn = AnimationUtils.loadAnimation(getActivity(), R.anim.push_bottom_o);//push_bottom_o    dropdown_in
        dropdownOut = AnimationUtils.loadAnimation(getActivity(), R.anim.push_bottom_i);//push_bottom_i   dropdown_out
        dropdownMaskOut = AnimationUtils.loadAnimation(getActivity(), R.anim.dropdown_mask_out);//push_bottom_o   dropdown_mask_out
        rotateIn= AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_in);
        rotateOut= AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_out);
        mask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setOpen(isOpen);
            }
        });
        for (int i = 0; i < title.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", title[i]);
            map.put("isChecked", false);
            scrrenList.add(map);
        }

        screenAdapter = new ScreenAdapter(getActivity(), scrrenList);
        screenAdapter.setOnIsSelectedCallBack(new ScreenAdapter.IsSelectedCallBack() {
            @Override
            public void isSelected(int position) {
                mask.performClick();
                setChcek(position);
            }
        });
        gridView.setAdapter(screenAdapter);

        view.findViewById(R.id.iv_add).setOnClickListener(new View.OnClickListener() {
            @Override
                public void onClick(View v) {
                    mask.performClick();
                }
        });
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        mScreenWidth=dm.widthPixels-dip2px(getActivity(),64);
        indicatorWidth = mScreenWidth/n;
        LayoutParams cursor_Params = mImgNavIndicatorView.getLayoutParams();
        cursor_Params.width = indicatorWidth;// 初始化滑动下标的宽
        mImgNavIndicatorView.setLayoutParams(cursor_Params);
        mHsv.setSomeParam(mRlnavView, iv_nav_left, iv_nav_right, getActivity());
        //获取布局填充器
       // mInflater = (LayoutInflater)getActivity().getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
       mInflater=LayoutInflater.from(getActivity());
        initNavigationHSV();


        mAdapter = new MyFragmentPageAdapter(this.getChildFragmentManager());
        mAdapter.fillFragments(BasicFragment.class,UploadFragment.class,BankCardFragment.class);
        //SuccessFragment.class   ApplySuccessFragment  FinancPlanFragment  FinancNoticeFragment   ApplyTheFragment
        //BankCardFragment    BankCardPrivateFragment
       // mAdapter.fillFragments(SuccessFragment.class,SuccessFragment.class,SuccessFragment.class);
        mViewPager.setAdapter(mAdapter);
    }

    private void initNavigationHSV() {
        mRgnavView.removeAllViews();
        for(int i=0;i<n;i++){
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(indicatorWidth , LinearLayout.LayoutParams.MATCH_PARENT);
            params.leftMargin = 5;
            params.rightMargin = 5;
            RadioButton rb = (RadioButton)mInflater.inflate(R.layout.item_nav_radiogroup,null);
            rb.setId(i);
            rb.setText(title[i]);
            rb.setPadding(5, 5, 5, 5);
            rb.setLayoutParams(params);
            mRgnavView.addView(rb);
        }
    }

    private void setListener() {
        /**加号的点击事件*/
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)mImgNavIndicatorView.getLayoutParams();
                int left=(int) (positionOffset * (mScreenWidth * 1.0 / n) + columnSelectIndex* (mScreenWidth / n));
                int margin=(int) (-(1 - positionOffset)* (mScreenWidth * 1.0 /n) + columnSelectIndex* (mScreenWidth / n));
                //第一种
           /*     if (columnSelectIndex == 0 && position == 0)// 0->1
                    lp.leftMargin =left;
                else if (columnSelectIndex == 1 && position == 1) // 1->2
                    lp.leftMargin =left;
                else if (columnSelectIndex == 2 && position == 2) // 2->3
                    lp.leftMargin = left;
                else if (columnSelectIndex == 3 && position == 3) // 3->4
                    lp.leftMargin = left;
                else if (columnSelectIndex == 4 && position == 5) // 4->5
                    lp.leftMargin = left;
				else if (columnSelectIndex == 5 && position == 6) // 5->6
					lp.leftMargin = (int) (offset * (indicatorWidth * 1.0 / 6) + columnSelectIndex* (indicatorWidth / 6));*/

               /* else if (columnSelectIndex == 1 && position == 0) // 1->0
                    lp.leftMargin =margin;
                else if (columnSelectIndex == 2 && position == 1) // 2->1
                    lp.leftMargin = margin;
                else if (columnSelectIndex == 3 && position == 2) // 3->2
                    lp.leftMargin =margin;
                else if (columnSelectIndex == 4 && position == 3) // 4->3
                    lp.leftMargin =margin;
                else if (columnSelectIndex == 5 && position ==4) // 5->4
                    lp.leftMargin =margin;
				else if (columnSelectIndex == 5 && position ==4) // 6->5
					lp.leftMargin = (int) (-(1 - offset)* (indicatorWidth * 1.0 / 6) + columnSelectIndex* (indicatorWidth / 6));*/

                //第二种
                lp.leftMargin=(int)(positionOffset * (mScreenWidth * 1.0 / n)+position*indicatorWidth);
                mImgNavIndicatorView.setLayoutParams(lp);
            }

            @Override
            public void onPageSelected(int position) {
                columnSelectIndex=position;
                if(mRgnavView!=null && mRgnavView.getChildCount()>position) {
                    ((RadioButton) mRgnavView.getChildAt(position)).performClick();
                    //  tv_center.setText(step.getList().get(position).getTagName());
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mRgnavView.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(mViewPager.getAdapter().getCount()==0||mViewPager.getAdapter().getCount()>checkedId){
                    if(mRgnavView.getChildAt(checkedId)!=null){
                        mViewPager.setCurrentItem(checkedId);	//ViewPager 跟随一起 切换
                       // tv_center.setText(step.getList().get(checkedId).getTagName());
                        //记录当前 下标的距最左侧的 距离
                        mHsv.smoothScrollTo(
                                (checkedId > 1 ? ((RadioButton) mRgnavView.getChildAt(checkedId)).getLeft() : 0) - ((RadioButton) mRgnavView.getChildAt(2)).getLeft(), 0);
                    }
                }
            }
        });


    }





    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


    private void setOpen(boolean isOpen) {
        if (isOpen) {
            openDropDown();
        } else {
            closeDropDown();
        }

        this.isOpen = !isOpen;
    }
    private void setChcek(int index){
        for (int i = 0; i < scrrenList.size(); i++) {
            if (i == index) {
                scrrenList.get(i).put("isChecked", true);
            } else {
                scrrenList.get(i).put("isChecked", false);
            }
        }
        screenAdapter.notifyDataSetChanged();
    }


    private void openDropDown() {
        mask.clearAnimation();
        iv_add.clearAnimation();
        rotateIn.setFillAfter(true);
        mask.setVisibility(View.VISIBLE);
        view1.clearAnimation();
        view1.startAnimation(dropdownIn);
        iv_add.startAnimation(rotateIn);
        view1.setVisibility(View.VISIBLE);
        tv_step.setVisibility(View.VISIBLE);
        mHsv.setVisibility(View.GONE);

    }
    private void closeDropDown() {
        mask.clearAnimation();
        iv_add.clearAnimation();
        mask.startAnimation(dropdownMaskOut);
        rotateOut.setFillAfter(true);
        iv_add.startAnimation(rotateOut);
        mask.setVisibility(View.GONE);
        view1.clearAnimation();
        view1.startAnimation(dropdownOut);
        view1.setVisibility(View.GONE);
        tv_step.setVisibility(View.GONE);
        mHsv.setVisibility(View.VISIBLE);

    }


    public  int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

}
